import logging
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from rest_framework import status


class TokenAuthentication(BaseAuthentication):
    def authenticate(self, request):
        # 1. 从请求中获取token
        # 2. 从数据库中获取token
        # 3. 返回(user, token)
        token = request.query_params.get("token")
        user = "User-Default"

        logging.info(f">>>>>>> the user is {user} and token: {token}")
        if token and user:
            return (user, token)
        raise AuthenticationFailed({"status code": status.HTTP_401_UNAUTHORIZED, "message": "It's not authorized"})

    def authenticate_header(self, request):
        """HTTP Status Code状态码一致性

        因为在 在`APIView` -> `dispatch()` -> `handle_exception` 定义了，如果`authenticate_header`没有定义，那么就会返回`HTTP_403_FORBIDDEN`
        ```python
         auth_header = self.get_authenticate_header(self.request)

            if auth_header:
                exc.auth_header = auth_header
            else:
                exc.status_code = status.HTTP_403_FORBIDDEN
        ```

        也可以参考 `BasicAuthentication` 弹出窗口，输入用户名和密码
        ```python
        def authenticate_header(self, request):
            return 'Basic realm="%s"' % self.www_authenticate_realm
        ```


        Args:
            request (_type_): _description_

        Returns:
            _type_: _description_
        """
        return "Token"
